package com.tanhua.dubbo.api.mongo.impl;

import com.tanhua.dubbo.api.mongo.VisitorsApi;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveOrUpdate(Visitors visitors) {
        Query query = new Query(Criteria.where("visitorUserId").is(visitors.getVisitorUserId()).and("userId").is(visitors.getUserId()).and("visitDate").is(visitors.getVisitDate()));
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        } else {
            Update update = new Update();
            update.set("date",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,Visitors.class);
        }
    }

    @Override
    public List<Visitors> queryVisitorsList(Long id, Long lastTime) {
        Criteria criteria = Criteria.where("userId").is(id);
        if(lastTime!=null){
            criteria.and("date").gt(lastTime);
        }
        Query query = new Query(criteria);
        query.limit(5).with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }
}
